package com.yachang.qym.usbhost.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.nkzawa.emitter.Emitter;
import com.squareup.leakcanary.RefWatcher;
import com.yachang.qym.usbhost.R;
import com.yachang.qym.usbhost.UsbApplication;
import com.yachang.qym.usbhost.activity.GroupManagerActivity;
import com.yachang.qym.usbhost.activity.MessageActivity;
import com.yachang.qym.usbhost.adapter.ContactAdapter;
import com.yachang.qym.usbhost.adapter.NetContactAdapter;
import com.yachang.qym.usbhost.model.ContactModel;
import com.yachang.qym.usbhost.model.OutPoliceModel;
import com.yachang.qym.usbhost.utils.API;
import com.yachang.qym.usbhost.utils.AllData;
import com.yachang.qym.usbhost.utils.SendData;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.yachang.qym.usbhost.utils.API.mSocket;

/**
 * Created by qym on 2015/12/21.
 */
public class ContactsFragment extends Fragment {

    private View mParentView;
    private ContactAdapter mGroupAdapter;
    private NetContactAdapter mPersonAdapter;
    private RelativeLayout mLayoutGroup;
    private List<ContactModel> contactModels = new ArrayList<>();
    private List<OutPoliceModel> personModels = new ArrayList<>();
    private RelativeLayout mCallAllLayout;
    private RelativeLayout mGroupContacts;
    private RelativeLayout mPersonContacts;
    private ListView mLvGroup;
    private ListView mLvPerson;
    private boolean groupOpen = false;
    private boolean personOpen = false;

    private Emitter.Listener onEnterPolice = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OutPoliceModel data = new OutPoliceModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        try {
                            JSONObject result = jsonObject.getJSONObject("result");
                            data = gson.fromJson(String.valueOf(result), OutPoliceModel.class);
                            boolean isIn = false;
                            for (int i = 0; i < personModels.size(); i++) {
                                if (personModels.get(i).get_id().equals(data.get_id())) {
                                    isIn = true;
                                }
                                if (personModels.get(i).getUid().equals(data.getUid())) {
                                    personModels.remove(i);
                                    personModels.add(data);
                                    mPersonAdapter.mModels = personModels;
                                    mPersonAdapter.notifyDataSetChanged();
                                }
                            }
                            if (!isIn) {
                                personModels.add(data);
                                mPersonAdapter.mModels = personModels;
                                mPersonAdapter.notifyDataSetChanged();
                            }
                            AllData.outPoliceModels = new ArrayList<OutPoliceModel>();
                            AllData.outPoliceModels = personModels;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    };

    private Emitter.Listener onExitPolice = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OutPoliceModel data = new OutPoliceModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        data = gson.fromJson(String.valueOf(jsonObject), OutPoliceModel.class);
                        if (data != null) {
                            for (Iterator<OutPoliceModel> it = personModels.iterator(); it.hasNext();) {
                                OutPoliceModel value = it.next();
                                if (value.get_id().equals(data.get_id())) {
                                    it.remove();
                                }
                            }
                        }
                        mPersonAdapter.mModels = personModels;
                        mPersonAdapter.notifyDataSetChanged();
                        AllData.outPoliceModels = new ArrayList<OutPoliceModel>();
                        AllData.outPoliceModels = personModels;
                    }
                });
            }
        }
    };

    private Emitter.Listener onChangeAddress = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            if(getActivity() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        OutPoliceModel data = new OutPoliceModel();
                        Gson gson = new Gson();
                        JSONObject jsonObject = (JSONObject) args[0];
                        data = gson.fromJson(String.valueOf(jsonObject), OutPoliceModel.class);
                        boolean isIn = false;
                        for (int i = 0; i < personModels.size(); i++) {
                            if (personModels.get(i).get_id().equals(data.get_id())) {
                                isIn = true;
                                break;
                            }
                        }
                        if (!isIn) {
                            personModels.add(data);
                            mPersonAdapter.mModels = personModels;
                            mPersonAdapter.notifyDataSetChanged();
                        }

                        AllData.outPoliceModels = new ArrayList<OutPoliceModel>();
                        AllData.outPoliceModels = personModels;
                    }
                });
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mParentView = inflater.inflate(R.layout.fragment_contacts, container, false);
        for(int i = 0; i < AllData.contactModels.size(); i++){
            if(AllData.contactModels.get(i).getStyle() != 1){
                contactModels.add(AllData.contactModels.get(i));
            }
        }
        initView();

        mSocket.on("inPolice", onEnterPolice);
        mSocket.on("outPolice", onExitPolice);
        mSocket.on("address", onChangeAddress);
        return mParentView;
    }

    private void initView() {

        mLvGroup = (ListView) mParentView.findViewById(R.id.lv_group_contacts);
        mGroupContacts = (RelativeLayout) mParentView.findViewById(R.id.layout_group_contacts);
        mGroupAdapter = new ContactAdapter(getActivity(), contactModels);
        mLvGroup.setAdapter(mGroupAdapter);

        //判断是否是指挥机
        if (false) {
            mGroupContacts.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (groupOpen) {
                        mLvGroup.setVisibility(View.GONE);
                        groupOpen = false;
                    } else {
                        mLvGroup.setVisibility(View.VISIBLE);
                        groupOpen = true;
                    }
                }
            });
            mLvGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    new AlertDialog.Builder(getActivity()).setTitle("临时重组").setIcon(R.drawable.icon).setMessage("确定与 " + contactModels.get(position).getName() + " 临时重组？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    SendData.data = SendData.sendGroupCall(contactModels.get(position).getCallID());
                                    SendData.needSend = true;
                                    dialog.dismiss();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                }
            });
        }

        mLvPerson = (ListView) mParentView.findViewById(R.id.lv_person_contacts);
        mPersonContacts = (RelativeLayout) mParentView.findViewById(R.id.layout_person_contacts);

        if (false) {
            mPersonContacts.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (personOpen) {
                        mLvPerson.setVisibility(View.GONE);
                    } else {
                        mLvPerson.setVisibility(View.VISIBLE);
                    }
                    personOpen = !personOpen;
                }
            });
        }
        mLvPerson.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                /*new AlertDialog.Builder(getActivity()).setTitle("临时重组").setIcon(R.drawable.icon).setMessage("确定与 " + personModels.get(position).getUserName() + " 临时重组？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SendData.data = SendData.sendContactCall(SendData.int2byte(Integer.parseInt(personModels.get(position).getMid())));
                                SendData.needSend = true;
                                dialog.dismiss();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();*/
                Intent intent = new Intent(getActivity(), MessageActivity.class);
                intent.putExtra("senderId", personModels.get(position).get_id());
                intent.putExtra("senderName", personModels.get(position).getUserName());
                String uid = personModels.get(position).getUid();
                intent.putExtra("senderUid", uid);
                intent.putExtra("senderMid", personModels.get(position).getMid());
                startActivity(intent);
            }
        });
        mPersonAdapter = new NetContactAdapter(getActivity(), personModels);
        mLvPerson.setAdapter(mPersonAdapter);

        mLayoutGroup = (RelativeLayout) mParentView.findViewById(R.id.layout_group);
        mCallAllLayout = (RelativeLayout) mParentView.findViewById(R.id.layout_call_all);
        mLayoutGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GroupManagerActivity.class);
                startActivity(intent);
            }
        });
        if (false){
            mCallAllLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new AlertDialog.Builder(getActivity()).setTitle("临时重组").setIcon(R.drawable.icon).setMessage("确定与 所有人 组临时重组？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    SendData.data = SendData.sendCallAll();
                                    SendData.needSend = true;
                                    dialog.dismiss();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                }
            });
    }
    }


    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = UsbApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }
}
